﻿using System.Collections.Generic;
using System.Text;
using System.Web;

namespace FluentWebRequest
{
    internal class RequestType : IRequestType
    {
        private readonly IRequestMethodFactory _requestMethodFactory;
        private readonly IDictionary<string, string> _requestItems;
        private readonly string _url;
        private string _parametters;

        public RequestType(string url, IDictionary<string, string> requestItems)
            : this(new RequestMethodFactory(), url, requestItems)
        {
        }

        public RequestType(IRequestMethodFactory requestMethodFactory, string url, IDictionary<string, string> requestItems)
        {
            _requestMethodFactory = requestMethodFactory;
            _url = url;
            _requestItems = requestItems;
        }

        public IRequestType BuildUrl()
        {
            foreach (var item in _requestItems)
            {
                _parametters += BuildOneItem(item.Key, item.Value);
            }

            return this;
        }

        public string GetDataFromUrl()
        {
            return _requestMethodFactory.GetDataFromUrl(_url, _parametters, RequestMethodType.Get);
        }

        private static string BuildOneItem(string key, string value)
        {
            var builder = new StringBuilder();
            return builder.AppendFormat("&{0}={1}", key, HttpUtility.UrlDecode(value)).ToString();
        }
    }
}